from django.shortcuts import render
from django.views import View
from apps.users.models import User
from django import http
import logging
import json
import re

# Create your views here.

# 创建日志生成器
logger = logging.getLogger('django')


class RegisterView(View):
    """实现注册逻辑
    POST http://www.meiduo.site:8000/register/
    """
    def post(self, request):
        # 接收请求数据
        json_bytes = request.body   # 返回的是字节类型
        json_str = json_bytes.decode()
        json_dict = json.loads(json_str)
        # json_dict = json.loads(request.body.decode())
        username = json_dict.get('username')
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        mobile = json_dict.get('mobile')
        allow = json_dict.get('allow')

        # 检验参数
        if not all([username, password, password2, mobile, allow]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必要的参数'})

        if not re.match('^[a-zA-Z0-9_-]{5,20}$', username):
            return http.JsonResponse({'code': 400, 'errmsg': 'username格式不对'})

        if not re.match('^[a-zA-Z0-9]{8,20}$', password):
            return http.JsonResponse({'code': 400, 'errmsg': 'password格式不对'})

        if password2 != password:
            return http.JsonResponse({'code': 400, 'errmsg': '两次输入密码不一样'})

        if not re.match('^1[3-9][0-9]{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': 'mobile格式不对'})

        if allow != True:
            return http.JsonResponse({'code': 400, 'errmsg': 'allow格式不对'})

        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)

        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '保存数据到数据库失败'})

        return http.JsonResponse({'code': 0, 'errmsg': 'ok'})


class UsernameCountView(View):
    """验证用户名是否重复
    GET http://www.meiduo.site:8000/usernames/itcast/count/
    """
    def get(self, request, username):
        try:
            count = User.objects.filter(username=username).count()

        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '访问数据库失败'})

        return http.JsonResponse({'code': 0, 'errmsg': 'OK', 'count': count})


class MobileCountView(View):
    """验证手机号码是否重复
    GET http://www.meiduo.site:8000/mobiles/15816120816/count/
    """
    def get(self, request, mobile):
        try:
            count = User.objects.filter(mobile=mobile).count()

        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '访问数据库失败'})

        return http.JsonResponse({'code': 0, 'errmsg': 'OK', 'count': count})

